// See the Electron documentation for details on how to use preload scripts:
// https://www.electronjs.org/docs/latest/tutorial/process-model#preload-scripts

const { contextBridge, ipcRenderer } = require('electron')

let _checkBeforeCloseHandler = null

contextBridge.exposeInMainWorld('electronAPI', {
  // 文件操作相关
  openFile: () => ipcRenderer.invoke('open-file'),
  saveFile: (content, filePath) => ipcRenderer.invoke('save-file', content, filePath),
  saveFileAs: (content) => ipcRenderer.invoke('save-file-as', content),
  
  // 系统打印
  print: () => ipcRenderer.invoke('print'),
  
  // 导出功能
  exportHTML: (content, title) => ipcRenderer.invoke('export-html', content, title),
  exportPDF: (content, title) => ipcRenderer.invoke('export-pdf', content, title),
  
  // 图片保存
  saveImage: (imageBuffer, fileName) => ipcRenderer.invoke('save-image', imageBuffer, fileName),
  
  // 获取应用信息
  getAppVersion: () => ipcRenderer.invoke('get-app-version'),
  
  // 主题切换
  toggleTheme: () => ipcRenderer.invoke('toggle-theme'),
  
  // 日志记录
  logMessage: (level, message, ...args) => ipcRenderer.invoke('log-message', level, message, ...args),
  
  // 窗口控制
  minimizeWindow: () => ipcRenderer.invoke('minimize-window'),
  toggleMaximizeWindow: () => ipcRenderer.invoke('toggle-maximize-window'),
  closeWindow: () => ipcRenderer.invoke('close-window'),
  onWindowMaximized: (callback) => ipcRenderer.on('window-maximized', callback),
  
  // 接收主进程发送的事件
  onFileOpened: (callback) => ipcRenderer.on('file-opened', callback),
  onThemeChanged: (callback) => ipcRenderer.on('theme-changed', callback),
  
  // 渲染进程就绪信号 & 启动完成通知
  rendererReady: () => ipcRenderer.send('renderer-ready'),
  onStartupComplete: (callback) => ipcRenderer.on('startup-complete', callback),

  // 设置持久化（注册表）
  getSettings: () => ipcRenderer.invoke('get-settings'),
  saveSettings: (settings) => ipcRenderer.invoke('save-settings', settings),
  

  // 关闭前检查处理
  handleCheckBeforeClose: (callback) => {
    console.log('=== preload.js: 注册关闭前检查处理器 ===')
    console.log('callback类型:', typeof callback)
    _checkBeforeCloseHandler = callback
    console.log('处理器已注册到隔离环境变量 _checkBeforeCloseHandler')
  },
  callCheckBeforeClose: async () => {
    console.log('=== preload.js: 调用关闭前检查处理器 ===')
    if (typeof _checkBeforeCloseHandler === 'function') {
      try {
        const result = await _checkBeforeCloseHandler()
        console.log('处理器返回结果:', result)
        return result
      } catch (error) {
        console.error('调用处理器失败:', error)
        return false
      }
    }
    console.log('未注册关闭前检查处理器，默认允许关闭')
    return true
  }
})